import json
import requests
from loguru import logger
from common.path_config import DING_URL
from common.path_config import failed_tests


def ding_send_message():
    headers = {
        'Content-Type': 'application/json'
    }
    if len(failed_tests) == 0:
        context = "所有用例执行完成！"
        data = {
            "at": {
                "isAtAll": False
            },
            "text": {
                "content": context
            },
            "msgtype": "text"
        }
        response = requests.post(url=DING_URL, headers=headers, data=json.dumps(data), json=json)
    else:
        failed_tests.append('以上用例执行失败！')
        context = ' \n'.join(failed_tests)
        data = {
            "at": {
                "isAtAll": True
            },
            "text": {
                "content": context
            },
            "msgtype": "text"
        }
        response = requests.post(url=DING_URL, headers=headers, data=json.dumps(data), json=json)
    if json.loads(response.text).get('errcode') != 0:
        logger.error(response.text)
